#include "StdAfx.h"
#include "md5str.h"
extern "C"
{
#include "md5.h"
}

md5str::md5str(const char* str)
{
	unsigned char digest[MD5_DIGEST_LENGTH] = {0};
	MD5_CTX md5ctx;
	MD5_Init( &md5ctx );
	MD5_Update( &md5ctx, (unsigned char*)str, strlen(str) );
	MD5_Final( (unsigned char *)digest, &md5ctx );

	char* szmd5 = NULL;
	md5 = hex2str( &szmd5, digest );
	freestr( &szmd5 );
}


md5str::~md5str(void)
{
}

const char* md5str::c_str()
{
	return md5.c_str();
}

const char* md5str::hex2str(char** pstr, const unsigned char* arhex, int arlen/*=MD5_DIGEST_LENGTH*/)
{
	if ( pstr == NULL )
		return *pstr;

	static char hash[] = "0123456789abcdef";
	int strlen = arlen*2 + 1;
	*pstr = new char[ strlen ];
	memset( *pstr, 0, strlen );
	for ( int i = 0; i < arlen; i++ )
	{
		(*pstr)[ 2*i ] = hash[ (arhex[i]>>4)&0xf ];
		(*pstr)[ 2*i + 1 ] = hash[ arhex[i] & 0xf ];
	}
	return *pstr;
}

void md5str::freestr( char** pstr )
{
	if( pstr != NULL )
	{
		delete[] (*pstr);
	}
	*pstr = NULL;
}

